<template>
  <div class="profile-container">
    <div class="profile-card">
      <!-- 侧边栏 -->
      <div class="sidebar">
        <div class="user-card">
          <div class="avatar-wrapper">
            <el-avatar :size="100" :src="formatAvatarUrl(userInfo.avatar)" class="user-avatar">
              {{ userInfo.username ? userInfo.username.charAt(0).toUpperCase() : 'U' }}
            </el-avatar>
            <div class="avatar-edit" @click="triggerFileUpload">
              <el-icon><EditPen /></el-icon>
            </div>
            <input 
              type="file" 
              ref="fileInputRef" 
              class="hidden-input" 
              accept="image/*" 
              @change="handleAvatarChange"
            />
          </div>
          <h2 class="username">{{ userInfo.username }}</h2>
          <span class="user-role" :class="userInfo.role === 'USER' ? 'role-user' : 'role-admin'">
            {{ userInfo.role === 'USER' ? '普通用户' : '管理员' }}
          </span>
        </div>
        
        <div class="nav-tabs">
          <div 
            class="nav-tab" 
            :class="{ active: activeTab === 'info' }"
            @click="activeTab = 'info'"
          >
            <el-icon><User /></el-icon>
            <span>个人信息</span>
          </div>
          <div 
            class="nav-tab" 
            :class="{ active: activeTab === 'avatar' }"
            @click="activeTab = 'avatar'"
          >
            <el-icon><Picture /></el-icon>
            <span>修改头像</span>
          </div>
          <div 
            class="nav-tab" 
            :class="{ active: activeTab === 'password' }"
            @click="activeTab = 'password'"
          >
            <el-icon><Lock /></el-icon>
            <span>修改密码</span>
          </div>
        </div>
      </div>
      
      <!-- 内容区域 -->
      <div class="content">
        <!-- 个人信息 -->
        <transition name="fade" mode="out-in">
          <div v-if="activeTab === 'info'" key="info" class="info-panel">
            <h1 class="panel-title">个人信息</h1>
            
            <el-form 
              ref="userFormRef" 
              :model="userForm" 
              :rules="userRules" 
              label-position="top"
              class="profile-form"
            >
              <div class="form-grid">
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="userForm.username" placeholder="你的用户名">
                    <template #prefix>
                      <el-icon><User /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
                
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="userForm.email" placeholder="你的邮箱地址">
                    <template #prefix>
                      <el-icon><Message /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              
                <el-form-item label="手机号码" prop="phone">
                  <el-input v-model="userForm.phone" placeholder="你的手机号码">
                    <template #prefix>
                      <el-icon><Phone /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
                
                <el-form-item label="性别">
                  <el-radio-group v-model="userForm.gender" class="gender-options">
                    <el-radio label="男">
                      <el-icon><Male /></el-icon> 男
                    </el-radio>
                    <el-radio label="女">
                      <el-icon><Female /></el-icon> 女
                    </el-radio>
                    <el-radio label="保密">
                      <el-icon><Position /></el-icon> 保密
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </div>
              
              <el-form-item label="个人简介">
                <el-input 
                  v-model="userForm.bio" 
                  type="textarea" 
                  :rows="3" 
                  placeholder="分享你的个人简介..."
                ></el-input>
              </el-form-item>
              
              <div class="form-actions">
                <el-button type="primary" round @click="submitUserInfo" :loading="submittingInfo">
                  <el-icon><Check /></el-icon> 保存信息
                </el-button>
                <el-button round @click="resetUserInfo">
                  <el-icon><RefreshRight /></el-icon> 重置
                </el-button>
              </div>
            </el-form>
          </div>
          
          <!-- 头像设置 -->
          <div v-else-if="activeTab === 'avatar'" key="avatar" class="avatar-panel">
            <h1 class="panel-title">头像设置</h1>
            
            <div class="avatar-editor">
              <div class="current-avatar">
                <h3>当前头像</h3>
                <el-avatar :size="120" :src="formatAvatarUrl(userInfo.avatar)" class="preview-avatar">
                  {{ userInfo.username ? userInfo.username.charAt(0).toUpperCase() : 'U' }}
                </el-avatar>
              </div>
              
              <div class="avatar-upload">
                <h3>上传新头像</h3>
                <el-upload
                  class="uploader"
                  action="#"
                  :auto-upload="false"
                  :show-file-list="false"
                  :on-change="handleAvatarPreview"
                  drag
                >
                  <div v-if="!avatarPreview" class="upload-placeholder">
                    <el-icon class="upload-icon"><Upload /></el-icon>
                    <div class="upload-text">拖拽图片到此处，或<em>点击上传</em></div>
                    <p class="upload-hint">支持JPG、PNG格式，文件大小不超过2MB</p>
                  </div>
                  <img v-else :src="avatarPreview" class="preview-image" />
                </el-upload>
                
                <div class="avatar-actions" v-if="avatarPreview">
                  <el-button type="primary" round @click="uploadAvatar" :loading="uploading">
                    <el-icon><Check /></el-icon> 保存头像
                  </el-button>
                  <el-button round @click="cancelUpload">
                    <el-icon><Close /></el-icon> 取消
                  </el-button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 密码修改 -->
          <div v-else-if="activeTab === 'password'" key="password" class="password-panel">
            <h1 class="panel-title">修改密码</h1>
            
            <el-form 
              ref="pwdFormRef" 
              :model="pwdForm" 
              :rules="pwdRules" 
              label-position="top"
              class="profile-form"
            >
              <el-form-item label="当前密码" prop="oldPassword">
                <el-input 
                  v-model="pwdForm.oldPassword" 
                  type="password" 
                  placeholder="输入当前密码"
                  show-password
                >
                  <template #prefix>
                    <el-icon><Key /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              
              <el-form-item label="新密码" prop="newPassword">
                <el-input 
                  v-model="pwdForm.newPassword" 
                  type="password" 
                  placeholder="设置新密码（6-20位字符）"
                  show-password
                >
                  <template #prefix>
                    <el-icon><EditPen /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              
              <el-form-item label="确认新密码" prop="confirmPassword">
                <el-input 
                  v-model="pwdForm.confirmPassword" 
                  type="password" 
                  placeholder="再次输入新密码"
                  show-password
                >
                  <template #prefix>
                    <el-icon><Check /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              
              <div class="form-actions">
                <el-button type="primary" round @click="submitPassword" :loading="submittingPwd">
                  <el-icon><Check /></el-icon> 修改密码
                </el-button>
                <el-button round @click="resetPassword">
                  <el-icon><RefreshRight /></el-icon> 重置
                </el-button>
              </div>
            </el-form>
          </div>
        </transition>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { 
  User, Lock, Picture, EditPen, Check, RefreshRight, 
  Close, Upload, Message, Phone, Male, Female, 
  Position, Key
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const router = useRouter()
const userStore = useUserStore()
const userFormRef = ref(null)
const pwdFormRef = ref(null)
const activeTab = ref('info')
const submittingInfo = ref(false)
const submittingPwd = ref(false)
const fileInputRef = ref(null)
const avatarFile = ref(null)
const avatarPreview = ref('')
const uploading = ref(false)
const API_BASE_URL = process.env.VUE_APP_BASE_API || '/api'

// 用户信息
const userInfo = computed(() => userStore.userInfo || {})

// 格式化头像URL，确保包含API前缀
const formatAvatarUrl = (url) => {
  if (!url) return ''
  
  // 如果已经是完整URL(包含http或https)，则直接返回
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  
  // 如果已经包含API前缀，则直接返回
  if (url.startsWith(API_BASE_URL)) {
    return url
  }
  
  // 否则添加API前缀
  return `${API_BASE_URL}${url.startsWith('/') ? '' : '/'}${url}`
}

// 表单数据
const userForm = reactive({
  id: '',
  username: '',
  email: '',
  phone: '',
  gender: '保密',
  bio: ''
})

// 密码表单
const pwdForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 校验规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度应为2-20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

const pwdRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应为6-20个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== pwdForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

// 初始化用户信息
onMounted(() => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  // 初始化表单数据
  fetchUserInfo()
})

// 获取用户详细信息
const fetchUserInfo = async () => {
  try {
    await request.get(`/user/${userStore.userInfo.id}`, {}, {
      showDefaultMsg: false,
      onSuccess: (data) => {
        // 更新表单数据
        Object.assign(userForm, data || {})
      }
    })
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 触发文件上传
const triggerFileUpload = () => {
  fileInputRef.value.click()
}

// 处理头像预览
const handleAvatarPreview = (file) => {
  avatarFile.value = file.raw
  avatarPreview.value = URL.createObjectURL(file.raw)
}

// 处理头像选择
const handleAvatarChange = (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  // 校验文件大小和类型
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2
  
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return
  }
  
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
    return
  }
  
  avatarFile.value = file
  avatarPreview.value = URL.createObjectURL(file)
  activeTab.value = 'avatar' // 切换到头像设置选项卡
}

// 上传头像
const uploadAvatar = async () => {
  if (!avatarFile.value) {
    ElMessage.warning('请先选择头像图片')
    return
  }
  
  uploading.value = true
  
  try {
    // 创建FormData对象
    const formData = new FormData()
    formData.append('file', avatarFile.value)
    
    // 调用上传接口
    await request.post('/file/upload/img', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      successMsg: '头像上传成功',
      onSuccess: (data) => {
        // 确保avatarUrl包含API前缀
        const avatarUrl = data
        
        // 更新用户头像
        updateUserAvatar(avatarUrl)
      }
    })
  } catch (error) {
    console.error('头像上传失败:', error)
  } finally {
    uploading.value = false
  }
}

// 更新用户头像信息
const updateUserAvatar = async (avatarUrl) => {
  try {
    // 确保存储到数据库的是不带API前缀的相对路径
    const relativePath = avatarUrl.replace(API_BASE_URL, '')
    
    await request.put(`/user/${userForm.id}`, {
      ...userForm,
      avatar: relativePath
    }, {
      successMsg: '头像更新成功',
      onSuccess: (data) => {
        // 更新本地用户信息
        userStore.updateUserInfo({
          ...userStore.userInfo,
          avatar: relativePath
        })
        
        // 重置头像上传状态
        cancelUpload()
      }
    })
  } catch (error) {
    console.error('更新用户头像失败:', error)
  }
}

// 取消上传
const cancelUpload = () => {
  avatarFile.value = null
  avatarPreview.value = ''
  if (fileInputRef.value) {
    fileInputRef.value.value = ''
  }
}

// 提交用户信息修改
const submitUserInfo = () => {
  userFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    submittingInfo.value = true
    
    try {
      await request.put(`/user/${userForm.id}`, userForm, {
        successMsg: '个人信息更新成功',
        onSuccess: (data) => {
          // 更新本地用户信息
          userStore.updateUserInfo({
            ...userStore.userInfo,
            ...userForm
          })
        }
      })
    } catch (error) {
      console.error('更新用户信息失败:', error)
    } finally {
      submittingInfo.value = false
    }
  })
}

// 重置个人信息表单
const resetUserInfo = () => {
  Object.assign(userForm, userInfo.value)
  userFormRef.value.resetFields()
}

// 提交密码修改
const submitPassword = () => {
  pwdFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    submittingPwd.value = true
    
    try {
      await request.put(`/user/${userInfo.value.id}/password`, null, {
        params: {
          oldPassword: pwdForm.oldPassword,
          newPassword: pwdForm.newPassword
        },
        successMsg: '密码修改成功，请重新登录',
        onSuccess: () => {
          // 退出登录，重新登录
          userStore.logout()
          router.push('/login')
        }
      })
    } catch (error) {
      console.error('修改密码失败:', error)
    } finally {
      submittingPwd.value = false
    }
  })
}

// 重置密码表单
const resetPassword = () => {
  pwdFormRef.value.resetFields()
}
</script>

<style lang="scss" scoped>
.profile-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;
  min-height: calc(100vh - 170px);
}

.profile-card {
  display: flex;
  gap: 30px;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  position: relative;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 8px;
    background: linear-gradient(90deg, #6366F1 0%, #8B5CF6 50%, #EC4899 100%);
  }
  
  .sidebar {
    width: 280px;
    background-color: #f8f9fc;
    padding: 30px 0;
    display: flex;
    flex-direction: column;
    border-right: 1px solid rgba(0, 0, 0, 0.05);
    
    .user-card {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 20px;
      margin-bottom: 20px;
      
      .avatar-wrapper {
        position: relative;
        margin-bottom: 16px;
        
        .user-avatar {
          border: 4px solid white;
          box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
          background: linear-gradient(45deg, #6366F1, #EC4899);
          transition: transform 0.3s ease;
          
          &:hover {
            transform: scale(1.05);
          }
        }
        
        .avatar-edit {
          position: absolute;
          bottom: 0;
          right: 0;
          width: 32px;
          height: 32px;
          background-color: #6366F1;
          border-radius: 50%;
          display: flex;
          justify-content: center;
          align-items: center;
          color: white;
          cursor: pointer;
          box-shadow: 0 2px 8px rgba(99, 102, 241, 0.4);
          transition: transform 0.2s;
          
          &:hover {
            transform: scale(1.1);
          }
        }
        
        .hidden-input {
          display: none;
        }
      }
      
      .username {
        font-size: 22px;
        font-weight: 600;
        margin: 0 0 8px;
        background: linear-gradient(90deg, #6366F1, #EC4899);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
      }
      
      .user-role {
        display: inline-block;
        padding: 4px 12px;
        border-radius: 20px;
        font-size: 14px;
        font-weight: 500;
        
        &.role-user {
          background-color: rgba(99, 102, 241, 0.1);
          color: #6366F1;
        }
        
        &.role-admin {
          background-color: rgba(236, 72, 153, 0.1);
          color: #EC4899;
        }
      }
    }
    
    .nav-tabs {
      display: flex;
      flex-direction: column;
      padding: 0 16px;
      
      .nav-tab {
        display: flex;
        align-items: center;
        padding: 14px 20px;
        margin-bottom: 8px;
        border-radius: 12px;
        cursor: pointer;
        transition: all 0.3s;
        font-weight: 500;
        color: #64748B;
        
        .el-icon {
          font-size: 18px;
          margin-right: 12px;
        }
        
        &:hover {
          background-color: rgba(99, 102, 241, 0.05);
          color: #6366F1;
        }
        
        &.active {
          background-color: rgba(99, 102, 241, 0.1);
          color: #6366F1;
          box-shadow: 0 2px 8px rgba(99, 102, 241, 0.1);
          
          &::after {
            content: '';
            position: absolute;
            right: 20px;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: #6366F1;
          }
        }
      }
    }
  }
  
  .content {
    flex: 1;
    padding: 40px;
    max-width: 800px;
    
    .panel-title {
      font-size: 28px;
      font-weight: 700;
      margin: 0 0 30px;
      color: #1E293B;
      position: relative;
      padding-bottom: 12px;
      
      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        width: 60px;
        height: 4px;
        background: linear-gradient(90deg, #6366F1, #EC4899);
        border-radius: 2px;
      }
    }
    
    .profile-form {
      .form-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 20px;
      }
      
      .el-form-item__label {
        font-weight: 600;
        color: #64748B;
      }
      
      .gender-options {
        display: flex;
        gap: 16px;
        
        .el-radio {
          margin-right: 0;
          padding: 8px 16px;
          border-radius: 8px;
          background-color: #f8f9fa;
          transition: all 0.2s;
          
          &.is-checked {
            background-color: rgba(99, 102, 241, 0.1);
          }
        }
      }
      
      .form-actions {
        display: flex;
        gap: 16px;
        margin-top: 24px;
        
        .el-button {
          padding: 12px 24px;
          font-weight: 600;
        }
      }
    }
    
    .avatar-editor {
      display: flex;
      gap: 40px;
      
      .current-avatar, .avatar-upload {
        flex: 1;
        
        h3 {
          font-size: 18px;
          font-weight: 600;
          margin: 0 0 20px;
          color: #1E293B;
        }
      }
      
      .current-avatar {
        display: flex;
        flex-direction: column;
        align-items: center;
        
        .preview-avatar {
          border: 4px solid white;
          box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        }
      }
      
      .avatar-upload {
        .uploader {
          width: 100%;
          
          .upload-placeholder {
            padding: 30px 20px;
            text-align: center;
            
            .upload-icon {
              font-size: 48px;
              color: #CBD5E1;
            }
            
            .upload-text {
              font-size: 16px;
              color: #64748B;
              margin: 12px 0;
              
              em {
                color: #6366F1;
                font-style: normal;
                font-weight: 600;
              }
            }
            
            .upload-hint {
              font-size: 14px;
              color: #94A3B8;
              margin: 0;
            }
          }
          
          .preview-image {
            width: 100%;
            height: 200px;
            object-fit: contain;
            border-radius: 8px;
          }
        }
        
        .avatar-actions {
          display: flex;
          gap: 16px;
          margin-top: 24px;
          justify-content: center;
        }
      }
    }
  }
}

// 动画
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s, transform 0.3s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(10px);
}

@media (max-width: 992px) {
  .profile-card {
    flex-direction: column;
    
    .sidebar {
      width: 100%;
      border-right: none;
      border-bottom: 1px solid rgba(0, 0, 0, 0.05);
      padding: 20px;
      
      .user-card {
        flex-direction: row;
        justify-content: flex-start;
        align-items: center;
        gap: 20px;
        
        .avatar-wrapper {
          margin-bottom: 0;
        }
      }
      
      .nav-tabs {
        flex-direction: row;
        justify-content: center;
        padding: 0;
        margin-top: 20px;
        
        .nav-tab {
          flex: 1;
          justify-content: center;
          padding: 10px;
          margin: 0 8px;
          
          .el-icon {
            margin-right: 8px;
          }
        }
      }
    }
    
    .content {
      padding: 30px 20px;
      
      .profile-form .form-grid {
        grid-template-columns: 1fr;
      }
      
      .avatar-editor {
        flex-direction: column;
      }
    }
  }
}

@media (max-width: 576px) {
  .profile-container {
    padding: 20px 10px;
  }
  
  .profile-card {
    .sidebar {
      .user-card {
        flex-direction: column;
        
        .username {
          font-size: 20px;
        }
      }
      
      .nav-tabs .nav-tab {
        font-size: 14px;
        margin: 0 4px;
        
        span {
          display: none;
        }
        
        .el-icon {
          margin-right: 0;
          font-size: 20px;
        }
      }
    }
    
    .content .panel-title {
      font-size: 24px;
    }
  }
}
</style> 